<?php
namespace app\api\controller;

use app\common\helper\Obj2Array;
use app\common\model\project_model\GuideModel;
use think\Controller;
use app\common\authtoken\token;
use app\common\httpdown\HttpRequest;
use app\common\aes\CryptAES;
use app\common\aes\WXBizDataCrypt;
use app\common\aes\Signature;
use think\cache\driver\Redis;
use think\Db;
use think\Exception;

/**
 * 用户注册 修改
 */
class Authlogin extends Controller
{

    /**
     * 用户注册
     * code
     * encryptedData
     * iv
     */
    public function authuser()
    {
        $ret['code'] = 1;

        if (request()->isPost()) {
            //小程序id默认为0，对应小程序信息中的数组下标
            $applet_id = input("applet_id","0");
            $ret['appletmsg'] = $applet_id;
            $islogin = input("islogin","0");
            $appletinfo = model("WechatAppletModel")->find($applet_id);
            $original_id = $appletinfo['original_id'];
            //redis获取appid和appsecret信息
            $redis = new Redis();
            $token_redis_key = "WX_CONFIG:OriginalId:".$original_id;

            $wx_config = $redis->get($token_redis_key);
            $wx_config = json_decode($wx_config, true);
            $appid = $wx_config['appid'];

            //解密appsecret
            $CryptAES = new CryptAES();
            $appsecret = $CryptAES->decrypt($wx_config['appsecret']);// 6R5W8HfrSwlM1lVORxG0KobamEOD5P7GCl1TS29547r92s3vf4QDno5ft9e6nDnb //993e6673af473ac7a280852f254e897d//151
            //var_dump($appsecret);die;
            //trace('错误信息$appid='.$appid.'|$appsecret='.$appsecret,'error');
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . trim($appid) . '&secret=' . trim($appsecret) . '&js_code=' . input('code') . '&grant_type=authorization_code';
            $http = new HttpRequest();

            $resuthtml = $http->https_request($url);

            try {
                if(empty($resuthtml)) {
                    $ret['msg'] = '请求微信接口失败';
                    return json($ret);
                }
                //拿到openid
                $jsonData = json_decode($resuthtml, true);
                //var_dump($jsonData);die;
                if($islogin == 1){
                    if(!isset($jsonData['session_key'])) {
                        $ret['msg'] = '请求微信接口session_key失败';
                        return json($ret);
                    }
                    $wxdecryted = new WXBizDataCrypt();
                    $wxdecryted->decryptData($appid, $jsonData['session_key'], input('encryptedData'), input('iv'), $decrypted);
                    $deData = json_decode($decrypted, true);
                }

            } catch (\Exception $e) {
                return json($e->getMessage());
            }

            $openid = $jsonData['openid'];
            if (empty($openid)) {
                $ret['msg'] = '资料不完整';
                return json($ret);
            }
            $data['original_id'] = $original_id;
            $data['openid'] = $openid;
            // updated_time
            $data['updated_time'] = date('Y-m-d H:i:s', time());
            if($islogin == 1){
                $data['nick_name'] = $deData['nickName'];
                $data['avatar_url'] = $deData['avatarUrl'];
                $data['gender'] = $deData['gender'];
                $data['city'] = $deData['city'];
                $data['province'] = $deData['province'];
                $data['country'] = $deData['country'];
                $data['language'] = $deData['language'];
                $data['applet_name'] = $appletinfo['name'];
            }
            //token
            $rankToken = new token();
            $data['token'] = $rankToken->randToken();

            try{
                $useMode = model('WechatUserModel')->where(['openid' => $openid])->find();
                if (empty($useMode)) {
                    $data['created_time'] = date('Y-m-d H:i:s', time());
                    // $data['score'] = 200;
                    $data['applet_id'] = $applet_id;
                    $insert_res = model('WechatUserModel')->insert($data);
                    if ($insert_res) {
                        $ret['code'] = 0;
                        $ret['token'] = $data['token'];
                    } else {
                        $ret['code'] = 1;
                        $ret['msg'] = '用户添加失败';
                    }
                } else {
                    $res = model('WechatUserModel')->where(['openid' => $openid])->update($data);
                    $ret['code'] = 0;
                    $ret['token'] = $data['token'];//返回token
                }
            } catch (\Exception $e) {

            }
        }
       return json($ret);
    }

    /**
     * 服务端不做判断，微信端自行判断
     * 只返回引导
     * 第一次进入
     * 以及引导接口
     */
    public function first() {
        $applet_id = input("applet_id", "0");
        if (empty($applet_id)) {
            return json(['code' => 0, 'error' => '请传递参数applet_id']);
        }
        // 获取第一次的引导提示
        $guideM = new GuideModel();
        $guide = $guideM->where(['status' => GuideModel::STATUS_OK, 'applet_app_id' => $applet_id])->field('id, title, img_url')->find();
        if (empty($guide)) {
            return json(['code' => 0, 'error' => '请配置引导']);
        }

        return json(['code' => 1, 'msg' => 'success', 'data' => $guide]);
    }


    public function testRedis() {

        $config = [
            'host'       => '47.52.227.161',//'172.31.92.213',
            'port'       => 6379,
            'password'   => 'daniel_redis',
            'select'     => 0,
            'timeout'    => 0,
            'expire'     => 0,
            'persistent' => false,
            'prefix'     => '',
        ];
        $redisM = new Redis($config);
        $redisM->set('test_remote_conn', 'connect ok', 5);
        var_dump($redisM->get('test_remote_conn'));die;

        $ori = 'gh_b3f37856cff6';
        $tokenM = new \app\common\wx\Token();
        $token = $tokenM->getAccessToken($ori);
        var_dump($token);die;
    }

    /**
     * 包含用户的判断是否第一次进入，是则
     * 给出引导
     */
    /*public function first() {
        if (request()->isPost()) {
            //小程序id默认为0，对应小程序信息中的数组下标
            $applet_id = input("applet_id", "0");

            $code = input("code", '');
            if (empty($code) || empty($applet_id)) {
                return json(['code' => 0, 'error' => 'code和applet_id缺失']);
            }
            $ret['appletmsg'] = $applet_id;
            $appletinfo = model("WechatAppletModel")->find($applet_id);
            $original_id = $appletinfo['original_id'];
            //redis获取appid和appsecret信息
            $redis = new Redis();
            $token_redis_key = "WX_CONFIG:OriginalId:" . $original_id;

            $wx_config = $redis->get($token_redis_key);
            $wx_config = json_decode($wx_config, true);

            $appid = $wx_config['appid'];

            //解密appsecret
            $CryptAES = new CryptAES();
            $appsecret = $CryptAES->decrypt($wx_config['appsecret']);
            //$appsecret = '9c3617502dd8fecb241c67a5085bc6f2';
            //var_dump($wx_config); var_dump('<br/>' . $appsecret);die;
            //trace('错误信息$appid='.$appid.'|$appsecret='.$appsecret,'error');
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . trim($appid) . '&secret=' . trim($appsecret) . '&js_code=' . $code . '&grant_type=authorization_code';
            $http = new HttpRequest();

            try {
                $resuthtml = $http->https_request($url);
                if (empty($resuthtml)) {
                    throw new Exception('请求微信接口失败');
                }
                //拿到openid
                $jsonData = json_decode($resuthtml, true);
                //var_dump($jsonData);die;
                $openid = $jsonData['openid'];
                // 判断是否第一次进来
                $useMode = model('WechatUserModel')->where(['openid' => $openid])->find();

                if (empty($useMode)) { // 第一次
                    // 获取第一次的引导提示
                    $guideM = new GuideModel();
                    $guide = $guideM->where(['status' => GuideModel::STATUS_OK, 'applet_app_id' => $applet_id])->field('id, title, img_url')->find();
                    if (empty($guide)) {
                        throw new Exception('找不到该小程序下的引导');
                    }

                    return json(['code' => 1, 'msg' => 'success', 'data' => $guide]);
                } else {
                    return json(['code' => 0, 'msg' => '不是第一次登陆']);
                }
            }catch (\Exception $e) {
                return json(['code' => 0, 'error' => $e->getMessage()]);
            }
        }
    }*/
}